package contegor.scire.structure;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.Date;
import java.util.Map;
import java.util.TreeMap;

import com.drew.imaging.ImageMetadataReader;
import com.drew.imaging.ImageProcessingException;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;

import contegor.scire.core.ConceptImpl;
import contegor.scire.core.DuplicateElementException;
import contegor.scire.core.Id;
import contegor.scire.core.IdFragment;
import contegor.scire.core.TimestampIdFragment;
import contegor.scire.core.TransactionException;
import contegor.scire.core.TransactionId;
import contegor.scire.core.WrongStateException;

public class JpegsContainer extends FilesContainer {
  private static final long serialVersionUID = -5712058264440276483L;

  public static final String INTERNAL_DIR_FORMAT = "yyyy" + File.pathSeparator + "MM" + File.pathSeparator + "dd";

  public JpegsContainer(long creationTime, TransactionId transactionId, IdFragment idFragment, File root) throws WrongStateException, IOException {
    super(creationTime, transactionId, idFragment, root);
  }

  public JpegsContainer(long creationTime, TransactionId transactionId, String idFragment, String root) throws WrongStateException, IOException {
    super(creationTime, transactionId, idFragment, root);
  }

  public JpegsContainer(long creationTime, TransactionId transactionId, String idFragment, URI root) throws WrongStateException, IOException {
    super(creationTime, transactionId, idFragment, root);
  }

  public JpegsContainer(String idFragment, File root) throws WrongStateException, IOException {
    super(idFragment, root);
  }

  public JpegsContainer(String idFragment, String root) throws WrongStateException, IOException {
    super(idFragment, root);
  }

  @Override
  protected void setUpFixedLinks() {
    super.setUpFixedLinks();
  }

  @Override
  protected void createFixedLinks(ConceptImpl concept, File file, TransactionId transactionId) throws DuplicateElementException, TransactionException, WrongStateException {
    try {
      Map<Id,IdFragment> rawData = new TreeMap<Id, IdFragment>();
      rawData.put(CREATION_TIME, new TimestampIdFragment(getJPegCreationDate(file)));
      createFixedLinks(concept, file.lastModified(), transactionId, rawData);
    }
    catch (Exception ex) {
      throw new WrongStateException(ex);    
    }
  }

  private Date getJPegCreationDate(File jpeg) throws ImageProcessingException, IOException {
    Metadata metadata = ImageMetadataReader.readMetadata(jpeg);
    for (Directory dir: metadata.getDirectories())
      if ("Exif IFD0".equals(dir.getName()))
        return dir.getDate(306); // [Exif IFD0] Date/Time - 2010:07:24 13:15:53 {306 : 2010:07:24 13:15:53}
    return new Date(jpeg.lastModified());
  }
}